#include "PCH.h"
#include "..\Common.h"

SelectDialog::SelectDialog(HINSTANCE hAppInstance, int DlgResourceId)
{
	hInstance = hAppInstance;
	ResourceId = DlgResourceId;
}

BOOL SelectDialog::HandleMessage(UINT WindowMessage, WPARAM wParam, LPARAM lParam)
{
	switch(WindowMessage) {
		case WM_CLOSE:
			return OnClose(wParam, lParam);
		case WM_COMMAND:
			return OnCommand(wParam, lParam);
		case WM_INITDIALOG:
			return OnInitDialog(wParam, lParam);
		case WM_NCDESTROY:
			return OnNcDestroy(wParam, lParam);
		default:
			return FALSE;
	}
}

BOOL SelectDialog::OnCommand(WPARAM wParam, LPARAM lParam) {
	switch(HIWORD(wParam)) {
		case CBN_SELCHANGE: {
			HWND combo = GetDlgItem(WindowHandle, COMBO_STATE);
			if ((HWND)lParam == combo) {
				int index = (int)SendMessage(combo, CB_GETCURSEL, NULL, NULL);
				if (index != CB_ERR) {
					combo = GetDlgItem(WindowHandle, COMBO_SITE);
					ATH::Instance()->GetRadarSites()->FillSites(combo, index);
				}
			}
			return FALSE;
		}
	}

	switch(LOWORD(wParam)) {
		case COMMAND_CANCEL:
			DestroyWindow(WindowHandle);
			return FALSE;
		case COMMAND_OK: {
			int state = (int)SendDlgItemMessage(WindowHandle, COMBO_STATE, CB_GETCURSEL, NULL, NULL);
			int site = (int)SendDlgItemMessage(WindowHandle, COMBO_SITE, CB_GETCURSEL, NULL, NULL);
			if (state != CB_ERR && site != CB_ERR) {
				ATH::Instance()->GetRadarSites()->SetupRadarSite(state, site, 0);
				DestroyWindow(WindowHandle);	
			}
			return FALSE;
		}
		default:
			return FALSE;
	}
}

BOOL SelectDialog::OnClose(WPARAM wParam, LPARAM lParam)
{
	DestroyWindow(WindowHandle);

	return FALSE;
}

BOOL SelectDialog::OnInitDialog(WPARAM wParam, LPARAM lParam) {
	SetForegroundWindow(WindowHandle);
	SetClassLongPtr(WindowHandle, GCLP_HICON, (LONG_PTR)LoadIcon(hInstance, MAKEINTRESOURCE(ICON_ATH16)));
	HWND combo = GetDlgItem(WindowHandle, COMBO_STATE);
	ATH::Instance()->GetRadarSites()->FillStates(combo);
	return FALSE;
}

BOOL SelectDialog::OnNcDestroy(WPARAM wParam, LPARAM lParam)
{
	LRESULT lResult = DefWindowProc(WindowHandle, WM_NCDESTROY, wParam, lParam);

	SetWindowLongPtr(WindowHandle, GWLP_USERDATA, 0);

	delete this;

	return (BOOL)lResult;
}
